<template>
  <div>
    <el-form
      ref="ruleFormRef"
      style="max-width: 600px"
      :model="ruleForm"
      :rules="rules"
      label-width="auto"
      class="demo-ruleForm"
      :size="formSize"
      status-icon
    >
      <el-form-item label="姓名" prop="leaveName">
        <el-input v-model="ruleForm.leaveName" />
      </el-form-item>
      <el-form-item label="部门" prop="departmentId">
        <el-select
          v-model="ruleForm.departmentId"
          placeholder="请选择部门"
          style="width: 150px"
        >
          <el-option label="IT信息部" :value="1" />
          <el-option label="财务部" :value="2" />
          <el-option label="行政部" :value="3" />
          <el-option label="人力资源部" :value="4" />
        </el-select>
      </el-form-item>
      <el-form-item label="请假类别" prop="type">
        <el-checkbox-group v-model="ruleForm.leaveType">
          <el-checkbox value="事假" name="type"> 事假 </el-checkbox>
          <el-checkbox value="病假" name="type"> 病假 </el-checkbox>
          <el-checkbox value="婚假" name="type"> 婚假 </el-checkbox>
          <el-checkbox value="产假" name="type"> 产假 </el-checkbox>
          <el-checkbox value="补休" name="type"> 补休 </el-checkbox>
          <el-checkbox value="工伤" name="type"> 工伤 </el-checkbox>
          <el-checkbox value="其它" name="type"> 其它 </el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="请假时间" required>
        <el-col :span="11" style="margin-bottom: 15px">
          <el-form-item prop="startTime">
            <el-date-picker
              v-model="ruleForm.startTime"
              aria-label="请选择开始时间"
              type="datetime"
              placeholder="请选择开始时间"
              format="YYYY年MM月DD日 HH时"
              value-format="YYYY-MM-DD HH:mm"
              style="width: 100%"
              @change="handleStartTimeChange"
            />
          </el-form-item>
        </el-col>
        <el-col class="text-center" :span="2" style="margin-bottom: 15px">
          <span class="text-gray-500">&emsp;至</span>
        </el-col>
        <el-col :span="11" style="margin-bottom: 15px">
          <el-form-item prop="endTime">
            <el-date-picker
              v-model="ruleForm.endTime"
              aria-label="请选择开始时间"
              type="datetime"
              placeholder="请选择开始时间"
              format="YYYY年MM月DD日 HH时"
              value-format="YYYY-MM-DD HH:mm"
              style="width: 100%"
              @change="handleEndTimeChange"
            />
          </el-form-item>
        </el-col>
        <span>工时&emsp;</span>
        <el-form-item prop="leaveHours">
          <el-input
            v-model="ruleForm.leaveHours"
            @input="handleLeaveHoursChange"
          />
        </el-form-item>
        <span>报到时间&emsp;</span>
        <el-form-item prop="reportTime">
          <el-date-picker
            v-model="ruleForm.reportTime"
            aria-label="请选择报到时间"
            type="datetime"
            placeholder="请选择报到时间"
            format="YYYY年MM月DD日 hh时"
            value-format="YYYY-MM-DD hh:mm"
            style="width: 100%"
          />
        </el-form-item>
      </el-form-item>
      <el-form-item label="请假事由" prop="leaveReason">
        <el-input
          v-model="ruleForm.leaveReason"
          type="textarea"
          placeholder="请输入请假原因(最多140字)"
          show-word-limit
          maxlength="140"
        />
      </el-form-item>
      <el-form-item label="部门领导" prop="leaderName">
        <el-input v-model="ruleForm.leaderName" disabled />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          添加
        </el-button>
        <el-button @click="resetForm(ruleFormRef)">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import axios from "axios";
import { useRouter } from "vue-router";
import { useCounterStore } from "@/stores/counter";
const store = useCounterStore();
const router = useRouter();
import type { ComponentSize, FormInstance, FormRules } from "element-plus";

interface RuleForm {
  laId: number;
  leaveId: number;
  leaveName: string;
  departmentId: number;
  leaveType: string;
  startTime: string;
  endTime: string;
  leaveHours: number;
  reportTime: string;
  leaveReason: string;
  leaderName: string;
  leaderIds: string;
  statusId: number;
  statusName: string;
  createTime: string;
  isDeleted: false;
}

const formSize = ref<ComponentSize>("default");
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<RuleForm>({
  laId: 0,
  leaveId: store.user.userId,
  leaveName: store.user.userName,
  departmentId: store.user.departmentId,
  leaveType: "",
  startTime: "",
  endTime: "",
  leaveHours: 0,
  reportTime: "",
  leaveReason: "",
  leaderName: "",
  leaderIds: "",
  statusId: 0,
  statusName: "",
  createTime: "2025-03-05T10:49:14.644Z",
  isDeleted: false,
});

const locationOptions = ["Home", "Company", "School"];

const rules = reactive<FormRules<RuleForm>>({
  leaveReason: [
    { required: true, message: "请输入原因", trigger: "blur" },
    { min: 1, max: 140, message: "长度最多140字", trigger: "blur" },
  ],
});

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log("submit!");
    } else {
      console.log("error submit!", fields);
    }
  });
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

const options = Array.from({ length: 10000 }).map((_, idx) => ({
  value: `${idx + 1}`,
  label: `${idx + 1}`,
}));

// 处理开始时间改变
const handleStartTimeChange = () => {
  if (ruleForm.startTime && ruleForm.leaveHours) {
    const startTime = new Date(ruleForm.startTime);
    const endTime = new Date(
      startTime.getTime() + ruleForm.leaveHours * 60 * 60 * 1000
    );
    ruleForm.endTime = endTime.toISOString().slice(0, 16).replace("T", " ");
  }
  calculateLeaveHours();
};

// 处理结束时间改变
const handleEndTimeChange = () => {
  calculateLeaveHours();
};

// 处理请假工时改变
const handleLeaveHoursChange = () => {
  if (ruleForm.startTime && ruleForm.leaveHours) {
    const startTime = new Date(ruleForm.startTime);
    const endTime = new Date(
      startTime.getTime() + ruleForm.leaveHours * 60 * 60 * 1000
    );
    ruleForm.endTime = endTime.toISOString().slice(0, 16).replace("T", " ");
  }
  calculateLeaveHours();
};

// 处理报到时间改变
const handleReportTimeChange = () => {
  // 可以在这里添加更多报到时间相关的逻辑
};

// 计算工时的函数
const calculateLeaveHours = () => {
  const startTime = ruleForm.startTime;
  const endTime = ruleForm.endTime;

  if (startTime && endTime) {
    // 计算时间差（毫秒）
    const timeDiff =
      new Date(endTime).getTime() - new Date(startTime).getTime();
    // 将时间差转换为小时
    const hours = timeDiff / (1000 * 60 * 60);
    ruleForm.leaveHours = hours;
  } else {
    ruleForm.leaveHours = 0;
  }
};

const getleaderName = () => {
  axios
    .get("http://localhost:7081/api/Form/GetLeader", {
      params: {
        UserId: ruleForm.leaveId,
        DepId: ruleForm.departmentId,
      },
    })
    .then((res) => {
      if (res.data.code == 100) {
        console.log(ruleForm.leaveId, ruleForm.departmentId, res.data.data);
        ruleForm.leaderName = res.data.data;
      } else {
        ruleForm.leaderName = "";
      }
    });
};
onMounted(() => {
  getleaderName();
});
</script>

<style scoped>
</style>